<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Show extends CI_Controller {

	function __construct()
	{
		parent::__construct();
//		$this->output->enable_profiler(TRUE);
		$this->load->model('City_m','city');
		$this->load->model('Admin_m','admin');
		$this->load->helper('form');

		$user_id = $this->dx_auth->get_user_id();
		if(!$user_id){
			$city_id = $this->session->userdata('city_id');
			$city = $this->session->userdata('city');
			if(!$city_id || !$city){
				$this->_set_visitor_city_info();
			}
		}
	}

	function index()
	{
		$this->city('');
	}

	function expired($city_id='')
	{
		$this->city($city_id);
	}

	function city($city_id='', $get_all = false){
		//init
		$is_active=true;
		$order_type = 'total';
		$offset = 0;

		$user_id = $this->dx_auth->get_user_id();
		$is_login = $this->dx_auth->is_logged_in();
		$all_city = array();
		if(!$is_login){
        	$all_city = $this->city->get_all();
		}

		$city_id = intval($city_id);
		if($city_id <= 0){
			$city_id = $this->session->userdata('city_id');
			$city = $this->session->userdata('city');
		}else{
			$city = $this->city->get_city_by_id($city_id);
		}

		$this->load->model('Category_m','category');
		$user_cat = $this->category->get_user_all_category_status($user_id);
		$this->load->model('Goods_m','goods');
		$cat_count = $this->goods->get_lev2_category_goods_count($city_id,$is_active);

		$cat_arr = array();
		$all_cat_arr = array();
		foreach ($user_cat as $key1 => $lev1_cat){
			if($lev1_cat['data']){
				foreach ($lev1_cat['data'] as $key2 => $lev2_cat){
					if($get_all){
						$cat_arr[] = $lev2_cat['id'];
						$user_cat[$key1]['data'][$key2]['valid'] = 1;
					}elseif ($lev2_cat['valid'] > 0){
						$cat_arr[] = $lev2_cat['id'];
					}
					$all_cat_arr[] = $lev2_cat['id'];
				}
			}
		}

		$this->load->model('Goods_m','goods');
		$this->load->model('Site_m','sites');
		$all_goods = $this->goods->get_goods($city_id, $all_cat_arr,$is_active, 'start_time desc',0,-1,'all');
		$max_price = 0;
        $max_date = 0;
		$site_id_arr = array();

		foreach ($all_goods as $good_item){
            $unix_time = strtotime($good_item['close_time']);
            if($unix_time > $max_date){
                $max_date = $unix_time;
            }
			if($good_item['sale_price'] > $max_price){
				$max_price = $good_item['sale_price'];
			}
			if(!in_array($good_item['site_id'], array_keys($site_id_arr))){
				$site_id_arr[$good_item['site_id']] = 0;
			}
			$site_id_arr[$good_item['site_id']]++;
		}

        $max_left_date = ceil(($max_date - time()) / 86400);

		$all_site_info = $this->sites->get_site_by_id(array_keys($site_id_arr),'weight desc');
		if($is_login){
			$user_site = $this->sites->get_user_valid_site($user_id);
		}else{
			$user_site = 'all';
		}

	    $non_body_params = array('all_goods_count' => count($all_goods),
	    						'site_count' => count($site_id_arr));
		$goods_list_html = $this->_goods($city_id,$is_active, $cat_arr,$order_type,$offset,$user_site,false,$non_body_params);

		$data = array(
					'is_login' => $is_login,
					'all_city' => $all_city,
					'city_id' => $city_id,
					'city' => $city,
					'user_cat' => $user_cat,
					'cat_count' => $cat_count,
					'site_id_arr' => $site_id_arr,
					'max_price' => $max_price,
					'max_left_date' => $max_left_date,
					'all_site_info' => $all_site_info,
					'user_site' => $user_site,
					'goods_list_html' => $goods_list_html,
					'post_err' => $this->session->flashdata('err'),
					'post_email' => $this->session->flashdata('femail'),
					'post_city' => $this->session->flashdata('fcity')
				);

		$this->load->view('show', $data);
	}

	function goods($city_id, $is_active=true,$cat_lst = '-', $order_type = 'total',
					$site_list = '-',
					$start_price = 0, $end_price = -1,
				    $start_discount = 0, $end_discount = -1,
				    $start_timeleft=0, $end_timeleft=-1,
					$offset = 0
					){
		$city_id = intval($city_id);

		$cat_lst = $cat_lst=='-'?'':$cat_lst;
		$cat_arr_str = $cat_lst?explode('-',$cat_lst):array();
		$cat_arr = array();
		foreach ($cat_arr_str as $cat_str){
			if(intval($cat_str) > 0){
				$cat_arr[] = intval($cat_str);
			}
		}

		$site_list = $site_list=='-'?'':$site_list;
		$site_arr_str = $site_list?explode('-',$site_list):array();
		$site_arr = array();
		foreach ($site_arr_str as $site_str){
			if(intval($site_str) > 0){
				$site_arr[] = intval($site_str);
			}
		}

		$ret = $this->_goods($city_id,$is_active, $cat_arr, $order_type,$offset,
						$site_arr, true , array(),$start_price, $end_price, $start_discount, $end_discount,
	    				$start_timeleft, $end_timeleft);

		echo json_encode($ret);
	}

	function _goods($city_id, $is_active=true,$cat_arr = array(),
		$order_type = 'total', $offset = 0,
		$site_list = array(),$only_body = false, $non_body_param = array(),
		$start_price = 0, $end_price = -1,
	    $start_discount = 0, $end_discount = -1,
	    $start_timeleft=0, $end_timeleft=-1
		){
		if($order_type == 'price_a'){
			$order = 'sale_price asc';
		}elseif ($order_type == 'price_d'){
			$order = 'sale_price desc';
		}elseif ($order_type == 'salerate_a'){
			$order = 'sale_rate asc';
		}elseif ($order_type == 'salerate_d'){
			$order = 'sale_rate desc';
		}elseif ($order_type == 'closetime_a'){
			$order = 'close_time asc';
		}elseif ($order_type == 'closetime_d'){
			$order = 'close_time desc';
		}elseif ($order_type == 'starttime_a'){
			$order = 'start_time asc';
		}elseif ($order_type == 'starttime_d'){
			$order = 'start_time desc';
		}else{
			$order = '';
		}

		$this->load->model('City_m','city');
		$city = $this->city->get_city_by_id($city_id);
		$city = $city ? $city : '';
		$all_city = '全国' == $city ? array() : $this->city->get_all();

		$this->load->model('Goods_m','goods');
		$goods_total = $this->goods->get_goods_count($city_id,$cat_arr,$is_active,
						$site_list,
						$start_price, $end_price,
	    				$start_discount, $end_discount,
	    				$start_timeleft, $end_timeleft
	    				);
		$goods = $this->goods->get_goods($city_id, $cat_arr,$is_active, $order,$offset,-1,
						$site_list,
						$start_price, $end_price,
	    				$start_discount, $end_discount,
	    				$start_timeleft, $end_timeleft
	    				);

		$this->load->model('Category_m','category');
		$cat_info = array();
		$site_info = array();
		if($goods){
			$cat_info = $this->category->get_category($cat_arr);

			$this->load->model('Site_m','sites');
			$site_id_arr = array();
			foreach ($goods as $good){
				if(!in_array($good['site_id'], $site_id_arr)){
					$site_id_arr[] = $good['site_id'];
				}
			}
			$site_info = $this->sites->get_site_by_id($site_id_arr);
		}

//		$cat_str = $cat_arr?implode('-',$cat_arr):'-';
//		$this->load->library('pagination');
//		$base_url = site_url("show/city/$city_id/".($is_active?'1':'0').'/'.$cat_str."/$order_type").'/';
//		$pg_config['base_url'] = $base_url;
//		$pg_config['total_rows'] = $goods_total;
//		$pg_config['per_page'] = NUM_PER_PAGE;
//		$pg_config['uri_segment'] = 7;
//		$this->pagination->initialize($pg_config);
//		$page_links = $this->pagination->create_links();

//		$this->load->helper('text');
		$good_data = array(
			'city_id' => $city_id,
			'city' => $city,
			'all_city' => $all_city,
			'goods' => $goods,
			'goods_total' => $goods_total,
//			'page_links' => $page_links,
			'cat_info' => $cat_info,
			'site_info' => $site_info,
			'is_active' => $is_active,
			'order_type' => $order_type
//			'cat_str' => $cat_str
		);

		if($only_body){
			$html = $this->load->view('show/goods_body', $good_data, true);
			return array('count' => $goods_total,
						'html' => trim($html));
		}else{
			$good_data['all_goods_count'] = $non_body_param['all_goods_count'];
			$good_data['site_count'] = $non_body_param['site_count'];
			return $this->load->view('show/goods', $good_data, true);
		}
	}

	function _set_visitor_city_info(){
		$this->load->model('City_m','city');
		$this->load->library('ip');
		$city_info = $this->ip->get_city_info_by_ip();

		if($city_info && $city_info['city_id'] && $city_info['city']){
			$this->city->set_city_info_in_session($city_info['city_id'],$city_info['city']);
		}else{
			$this->city->set_city_info_in_session(2,'北京');
		}
	}

	function _get_template_map(){
		$res = $this->admin->get_common_templates();
		$template_map = array();
		foreach($res as $row){
			$template_map[$row->id] = $row->name;
		}
		return $template_map;
	}
  
  function cor() {
    $this->load->view('show/cor');
  }

	function about_ttz(){
		$this->load->view('show/about_ttz');
	}
  
  function open_api(){
		$this->load->view('show/open_api');
	}
  
  function user_pro(){
		$this->load->view('show/user_pro');
	}
  
  function qa(){
		$this->load->view('show/qa');
	}
  
  function chance(){
		$this->load->view('show/chance');
	}
  
  function submit_site(){
		$is_login = $this->dx_auth->is_logged_in();
		$all_city = array();
		if(!$is_login){
        	$all_city = $this->city->get_all();
		}

		$template_map = $this->_get_template_map();
		$data = array(
			'all_city' => $all_city,
			'prompt'		=> '',
			'template_map' 	=> $template_map,
			'post_err' => $this->session->flashdata('err'),
			'post_email' => $this->session->flashdata('femail'),
			'post_city' => $this->session->flashdata('fcity')
		);
		$this->load->view('show/submit_site', $data);
	}
	
	function submit_suggest(){
		$is_login = $this->dx_auth->is_logged_in();
		$all_city = array();
		if(!$is_login){
        	$all_city = $this->city->get_all();
		}

		$post = $this->input->post('post');
		$prompt = '';
		if($post){
			$name = $this->input->post('name');
			$contact = $this->input->post('contact');
			$content = $this->input->post('content');
			
			if(!$name || !$contact || !$content){
				$prompt = '提交失败，请正确填写每一项内容';
			}else{
				$this->load->model('Suggest_m','sugg');
				$this->sugg->add_suggest($name,$contact,$content);
				$prompt = '您的意见已成功提交，谢谢您的反馈!';
			}
		}
		
		$data = array(
				'all_city' => $all_city,
				'prompt' => $prompt,
				'name_input' => isset($name)?$name:'',
				'contact_input' => isset($contact)?$contact:'',
				'content_input' =>  isset($content)?$content:''
			);

		$this->load->view('show/submit_suggest', $data);
	}

	function addsite(){
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$val = $this->form_validation;

		// Set form validation rules
		$val->set_rules('site_name', '网站名', 'trim|required|xss_clean');
		$val->set_rules('site_url', '网站地址', 'trim|required|xss_clean|prep_url');
		$val->set_rules('xml_url', 'API抓取地址', 'trim|required|xss_clean|prep_url');
		$val->set_rules('api_template_id', 'API模板', 'trim|required|integer');

		$template_map = $this->_get_template_map();
		$data = array(
			'prompt'        => '',
			'template_map' 	=> $template_map
		);
		// Run form validation
		if ($val->run()) {
			$this->load->model('Site_m','site');
			$site = array(
						'site_name' => $val->set_value('site_name'),
						'site_url' => $val->set_value('site_url'),
						'xml_url' => $val->set_value('xml_url'),
						'api_template_id' => $val->set_value('api_template_id'),
						'status' => 0
					);
			if($this->site->create_site($site)){
				$data['prompt'] = '<div style="padding:10px;color:8EB000">已经成功提交  等待管理员审核</div>';
			}else{
				$data['prompt'] = '<div style="padding:10px;color:red">API 地址已存在，请勿重复提交</div>';
			}
		}else{
			$data['prompt'] = '<div style="padding:10px;color:red">请填写正确的信息</div>';
		}
		$this->load->view('show/submit_site', $data);

// 		ERROR   Load registration page
//		$this->load->view($this->dx_auth->register_view);
	}

	function mail($good_id){
		$is_login = $this->dx_auth->is_logged_in();
		$all_city = array();
		if(!$is_login){
        	$all_city = $this->city->get_all();
		}

		$this->load->model('Goods_m','goods');
		$good = $this->goods->get_good($good_id);
		if(!$good){
			return;
		}

		$this->load->model('Category_m','category');
		$cat_arr = array();
		$cat_arr[] = $good['cat_level2'];
		$cat_info = $this->category->get_category($cat_arr);
		$category = $cat_info[$good['cat_level2']]['cat_name'];

		$data = array(
					'all_city' => $all_city,
					'good' => $good,
					'category' => $category,
					'post_err' => $this->session->flashdata('err'),
					'post_email' => $this->session->flashdata('femail'),
					'post_city' => $this->session->flashdata('fcity')
				);
//		var_dump($data);
		$this->load->view('single_good', $data);
	}

	function test(){
//		$all_city = $this->city->get_all_from_config();
//		var_dump($all_city);
//		$time = '2011-04-19 00:00:00';
//		echo strtotime($time) > time() ? '还剩'.(int)((strtotime($time)-time())/3600).'小时' : '已结束';
//		echo date("Y-m-d H:i:s");
//		$this->load->model('Suggest_m','sugg');
//		var_dump($this->sugg->get_count());
//		$suggestion = $this->sugg->get_suggestion_by_id(1);
//		$suggestion = $this->sugg->get_paged_suggestion(1,2);
//		$this->sugg->add_suggest('qqqq','wwwww','eeeeeee');
//		$this->sugg->reply_suggest(6,'ccccccc');
//		var_dump($suggestion);
	}
}
